<template>
  <!-- 筛选查询头部 -->
  <div id="HeaderTopTow">
    <div id="DaiShenHeDingDan">
      <div class="login" v-if="show">
        <div class="topHeader">
          <!-- 搜索部分 -->
          <div class="searchRes">
            <div class="searchResleft">
              <ul>
                <!-- 隔离-- table表格组件 -->
                <li class="orderNumber" v-if="props.comOrderNumber">
                  <div class="isleft">订单号</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.orderNumber" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.entrustingUnit">
                  <div class="isleft">委托单位</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.entrustingUnit" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.entryNumber">
                  <div class="isleft">进仓号</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.entryNumber" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.customerNumber">
                  <div class="isleft">客户编号</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.customerNumber" :placeholder="placeholderValue" />
                  </div>
                </li>
                <!-- 隔离-- 树形表格的搜索 -->
                <li class="orderNumber" v-if="props.userName">
                  <div class="isleft">用户姓名</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.userName" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.gender">
                  <div class="isleft">性别</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.gender" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.status">
                  <div class="isleft">用户状态</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.status" :placeholder="placeholderValue" />
                  </div>
                </li>
                <li class="orderNumber" v-if="props.userId">
                  <div class="isleft">身份证号</div>
                  <div class="isright">
                    <el-input v-model="inputDataList.userId" :placeholder="placeholderValue" />
                  </div>
                </li>
              </ul>
            </div>
            <!-- 隔离-- 通用 -->
            <div class="searchRes-right">
              <div class="itemButton">
                <el-button type="success" plain @click="onSearch">查询</el-button>
                <el-button type="info" plain @click="onReset" class="gongNengBtn">重置</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="headerTopBuju">
        <!-- 待审核 -->
        <div class="left">
          <div class="grid-content ep-bg-purple" v-if="dsh">
            <el-button type="success" plain @click="gotoAdd">新增</el-button>
            <el-dropdown class="integration">
              <el-button type="primary" plain>
                批量操作&nbsp;
                <el-icon><ArrowDownBold /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="batchExport">批量导出</el-dropdown-item>
                  <el-dropdown-item @click="batchImport">批量导入</el-dropdown-item>
                  <el-dropdown-item @click="downloadTemplate">下载模板</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <!-- 隔离-- 进行中 -->
        <div class="left">
          <div class="grid-content ep-bg-purple" v-if="jxz">
            <el-button type="danger" plain @click="del"> 批量删除 </el-button>
          </div>
        </div>
        <!-- 已归档 -->
        <div class="left">
          <div class="grid-content ep-bg-purple" v-if="ygd">
            <el-button type="primary" plain @click="cancelYgd"> 撤销已归档 </el-button>
          </div>
        </div>
        <!-- 隔离-- 树形表格 -->
        <div class="left">
          <div class="grid-content ep-bg-purple" v-if="treeTbale">
            <el-button type="success" plain @click="onSearch">新增用户</el-button>
            <el-button type="success" plain @click="onSearch">批量添加</el-button>
            <el-button type="success" plain @click="onSearch">导出数据</el-button>
            <el-button type="success" plain @click="onSearch">打印数据</el-button>
          </div>
        </div>
        <!-- 隔离-- 通用 -->
        <div class="right">
          <div class="right-button">
            <div class="shaixuan">
              <div @click="ptOpenDowOrUp" class="wenzi" v-if="shai_xuan">
                {{ show ? '收起筛选' : '展开筛选' }}
              </div>
              <div class="icon">
                <!-- v-if="columns.length" @click="handlePrint" -->
                <el-icon v-if="show"><ArrowUpBold /></el-icon>
                <el-icon v-else><ArrowDownBold /></el-icon>
              </div>
            </div>
            <!-- 刷新 -->
            <div class="huishouzhan">
              <el-button :icon="Refresh" circle @click="reloadPage"> </el-button>
            </div>
            <!-- 打印 -->
            <div class="huishouzhan">
              <el-button :icon="Printer" circle @click="dayin"> </el-button>
            </div>
            <!-- 回收站 -->
            <div class="huishouzhan">
              <el-button :icon="MessageBox" circle @click="huishouzhan"> </el-button>
            </div>
            <!-- 表头设置 -->
            <div class="shezhi">
              <el-button :icon="Open" circle @click="tableSettin"> </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 控制表头是否显示 -->
    <el-dialog v-model="centerDialogVisible" title="列表设置" width="30%" destroy-on-close>
      <el-table
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        border
        stripe
        ref="multipleTableRef"
        :data="useTable.tableHeader"
        style="width: 100%"
        height="335"
      >
        <el-table-column property="lable" label="字段" align="center" />
        <el-table-column prop="isShow" align="center" label="显示" v-slot="scope">
          <el-switch v-model="scope.row.isShow"></el-switch>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="isShowQueDing"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 回收站 -->
    <el-dialog v-model="recyclingBin" title="回收站" width="80%" destroy-on-close>
      {{ '这是一个回收站表格' }}
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="centerDialogVisible = false"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="tableHeaderTop">
import { ElMessage } from 'element-plus'
import { dshList } from '@/data/tableData/tableType'
// 引入事件总线并切换路由的时候卸载
import bus from '@/libs/bus'
// 图标
import { MessageBox, Printer, Open, Refresh } from '@element-plus/icons-vue'
// 打印
import printJS from 'print-js'
// 引入仓库
import useStore from '@/stores'
const { useTable } = useStore()

const props = defineProps<{
  /**
   * @筛选查询头部
   * @param SHAI_XUAN        展开筛选  —必填项
   * @param comOrderNumber  号码     —可选项
   * @param nameOfShip      名称     —可选项
   * @param entryNumber      仓号     —可选项
   * @param entrustingUnit      单位     —可选项
   * @param customerNumber      编号     —可选项
   * @param dsh      待审核     —可选项
   * @param jxz      运行中     —可选项
   * @param ygd      已归档     —可选项
   * @param treeTbale     树形表格     —可选项
   * @param userName    用户名     —可选项
   * @param gender      性别     —可选项
   * @param status      状态     —可选项
   * @param userId      身份证     —可选项
   * */
  shai_xuan: 'true' | 'false'
  // 号码
  comOrderNumber?: 'true' | 'false'
  // 创建日期
  comOrderTime?: 'true' | 'false'
  // 名称
  nameOfShip?: 'true' | 'false'
  // 仓号
  entryNumber?: 'true' | 'false'
  // 单位
  entrustingUnit?: 'true' | 'false'
  // 编号
  customerNumber?: 'true' | 'false'
  // 待审核
  dsh?: 'true' | 'false'
  // 运行中
  jxz?: 'true' | 'false'
  // 已归档
  ygd?: 'true' | 'false'
  // 树形表格
  treeTbale?: 'true' | 'false'
  // 用户名
  userName?: 'true' | 'false'
  // 性别
  gender?: 'true' | 'false'
  // 状态
  status?: 'true' | 'false'
  // 身份证
  userId?: 'true' | 'false'
}>()

// 展开筛选的表单数据
const inputDataList = ref({
  // 待审核:订单号  // 运行中：订单编号
  orderNumber: '',
  // 待审核:创建日期
  creationTime: [],
  // 运行中:船名
  nameOfShip: '',
  // 运行中:委托单位
  entrustingUnit: '',
  // 运行中:进仓号
  entryNumber: '',
  // 状态
  orderStatus: '',
  // 编号
  customerNumber: '',
  // 用户名
  userName: '',
  // 性别
  gender: '',
  // 状态
  status: '',
  // 身份证
  userId: ''
})

const show = ref(false)
// 箭头向上向下
const ptOpenDowOrUp = () => {
  show.value = !show.value
}
const placeholderValue = ref('请输入')

// 触发待审核中的新增跳转路由
const gotoAdd = () => {
  // router.push('/orders/create/orderDetails')
}
// 隔离---------------------------------------------------------
// 查询
const onSearch = async () => {
  inputDataList.value.orderStatus = useTable.orderStatus
  // 必须填写订单号
  // if (['dsh', 'jxz', 'ygd'].includes(inputDataList.value.orderStatus) && !inputDataList.value.orderNumber) {
  //   const map: any = { dsh: '待审核', jxz: '进行中', ygd: '已归档' }
  //   ElMessage.error({ message: `请填写${map[useTable.orderStatus]}订单号` })
  //   return
  // }
  const res = useTable.dshList.find((item: any) => item === inputDataList.value)
  console.log('🚚...  查询的结果', res)
  if ([res].length === 0) {
    ElMessage.error({ message: `查询数据为空` })
    return
  } else if (res?.id) {
    useTable.searchDshList([res])
  }
}
// 隔离---------------------------------------------------------
// 重置
const onReset = () => {
  inputDataList.value = {
    // 待审核:订单号  // 运行中：订单编号
    orderNumber: '',
    // 待审核:创建日期
    creationTime: [],
    // 运行中:船名航次
    nameOfShip: '',
    // 运行中:委托单位
    entrustingUnit: '',
    // 运行中:进仓号
    entryNumber: '',
    // 客户管理：客户编号
    customerNumber: '',
    // 客户管理：公司抬头
    // 状态
    orderStatus: '',
    // 用户名
    userName: '',
    // 性别
    gender: '',
    // 状态
    status: '',
    // 身份证
    userId: ''
  }
  useTable.searchDshList(useTable.resetData)
}
// 隔离---------------------------------------------------------
// 控制表头是否显示
const centerDialogVisible = ref(false)
const tableSettin = () => {
  // 获取当前tabs的本地数据
  const arr = JSON.parse(sessionStorage.getItem(useTable.orderStatus) as any)
  // 将本地数据设置给pinia里的表头
  useTable.setTableList(arr)
  centerDialogVisible.value = true
}
// 自定义表头确定按钮
const isShowQueDing = () => {
  // 点击确定将表头数据存给tabs名字的本地数据
  sessionStorage.setItem(useTable.orderStatus, JSON.stringify(useTable.tableHeader))
  centerDialogVisible.value = false
}

// 隔离---------------------------------------------------------
// 回收站
const recyclingBin = ref(false)
const huishouzhan = () => {
  recyclingBin.value = true
}

// 隔离---------------------------------------------------------
// 打印表格数据（💥 多级表头数据打印时，只能扁平化成一维数组，printJs 不支持多级表头打印）
const dayin = () => {
  const printColumns = useTable.tableHeader.map((ele: any) => {
    return {
      field: ele.property,
      displayName: ele.lable
    }
  })
  // 表格头部内容
  const titleHeader = {
    dsh: '待审核表单',
    jxz: '进行中表单',
    ygd: '已归档表单'
  } as any
  // 表头的样式
  const headerStyle = ref(
    `<div style="display: flex;flex-direction: column;text-align: center"><h2>${
      titleHeader[useTable.orderStatus]
    }</h2></div>`
  )
  // 打印样式
  const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `

  printJS({
    // 打印的数据
    printable: useTable.printingList.length > 0 ? useTable.printingList : useTable.dshList,
    // header: 表头的样式
    header: headerStyle.value,

    properties: printColumns,
    type: 'json',
    //表格头部样式设置
    gridHeaderStyle: 'border: 1px solid #000;text-align:center',
    // 表格内容样式设置
    gridStyle: 'border: 1px solid #000;text-align:center',
    // 表格样式,必须和表格放在一起
    style: printStyle
  })
}

// 隔离---------------------------------------------------------
// 抽离出去 批量删除
const del = () => {
  bus.$emit('del')
  // useTable.tabsTableDelAll()
}
// 刷新当前页面
const reloadPage = () => {
  bus.$emit('reloadPage')
}
// 撤销已归档
const cancelYgd = () => {
  bus.$emit('cancelYgd')
}
// 抽离出去 待审核批量导出
const batchExport = () => {
  bus.$emit('batchExport')
}
// 待审核批量导入
const batchImport = () => {
  bus.$emit('batchImport')
}
// 待审核下载模板
const downloadTemplate = () => {
  bus.$emit('downloadTemplate')
}

// 隔离---------------------------------------------------------
// tab切换时卸载,监听 pinia 的数据
const subscribe = useTable.$subscribe(
  (mutation, state) => {
    console.log('🚚...  pinia监听')
  },
  { detached: false }
)
// 隔离---------------------------------------------------------
const unloading = () => {
  bus.$off('del', console.log(`🚒...卸载__ 批量删除`))
  // bus.$off('reloadPage', console.log(`🚒...卸载__ 刷新当前页面`))
}

// 隔离---------------------------------------------------------
// 每次路由改变都会卸载全局的eventbus
onBeforeUnmount(() => {
  // 停止订阅
  subscribe()
  // 卸载bus
  unloading()
})
</script>

<style lang="scss" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

#HeaderTopTow {
  padding: 0 15px;
  .integration {
    margin-left: 10px;
  }
  .searchRes {
    display: flex;
    justify-content: space-between;
    .searchResleft {
      width: 94%;
      ul {
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
        .orderNumber {
          height: 50px;
          margin-right: 10px;
          width: 19%;
          // 最小宽度
          min-width: 150px;
          // background-color: #fb8b05;
          display: flex;
          justify-content: start;
          align-items: center;
          .isleft {
            // width: 60px;
            font-size: 12px;
            margin-right: 10px;
          }
          .isright {
            flex: 1;
          }
        }
      }
    }

    .searchRes-right {
      .itemButton {
        display: flex;
        flex-flow: column;
        justify-content: center;
        .gongNengBtn {
          margin-top: 10px;
          margin-left: 0;
        }
      }
    }
  }
  .maxWidth {
    width: 25% !important;
  }
  .sides {
    margin: 0 5px;
  }
  .deleteBtn {
    margin-left: 0px;
  }
  #DaiShenHeDingDan {
    .headerTopBuju {
      margin: 10px 0;

      display: flex;
      justify-content: space-between;
      .right {
        display: flex;
        justify-content: end;
        flex: 1;
        .right-button {
          display: flex;
          align-items: center;
          .shaixuan {
            display: flex;
            align-items: center;
            border-right: 2px solid #ccc;
            width: 100px;
            cursor: pointer;
            margin: auto;
            color: #ccc;
            margin-right: 5px;
            .wenzi {
              margin-right: 5px;
            }
            .icon {
              height: 16px;
              color: #ccc;
            }
          }

          .shezhi,
          .huishouzhan {
            cursor: pointer;
            margin: 0 5px;
            font-size: 20px;
            // height: 20px;
            color: #ccc;
          }
        }
      }
    }
  }
}
</style>
